#include "logdetail.h"
#include "ui_logdetail.h"
#include <QMessageBox>
#include <QListView>
#include <QFileDialog>
#include <QPrintDialog>
#include <QTextDocument>
#include "shadow.h"
#include "msgbox.h"
#include "log4z.h"
#include "authmanager.h"
#include "udiskexport.h"
#include "loading.h"
#include "userlogger.h"
#include "customprinter.h"

using namespace zsummer::log4z;

LogDetail::LogDetail(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LogDetail)
{
    ui->setupUi(this);
    bdf = BllDataFlow::getInstance();
    sqlHelper = SqlHelper::getInstance();
    exportMgr = new UdiskExport(this);

    //Signals and Slots
    connect(bdf, &BllDataFlow::setWidgetVisibleSignal,this,&LogDetail::setWidgetVisibleSlot);
    connect(bdf, &BllDataFlow::retranslateUiSignal, this, &LogDetail::retranslateUiSlot);
    connect(bdf, &BllDataFlow::selectDateTimePickerSignal, this, &LogDetail::changeDateTime);
    connect(bdf, &BllDataFlow::setCurrentTimeSignal, this, &LogDetail::setCurrentTimeSlot);
    connect(exportMgr, &UdiskExport::done, this, &LogDetail::pdfSaveDone);

    dateTimePicker = new DateTimePicker(nullptr, DateTimeType::Date | DateTimeType::Hour | DateTimeType::Minute);

    initWidget();
}

LogDetail::~LogDetail()
{
    delete ui;
}

void LogDetail::save(const QString &path)
{
    MyOffice().savePdf(path, contentHtml);
}

void LogDetail::on_btnExport_clicked()
{
    Loading::showLoading(QColor(0,0,0,200), false, tr("exporting..."));
    UserLogger::log(QString(tr("Export %1")).arg(ui->cbxLogType->currentText()));
    exportMgr->exports(ReportType::LOG_REPORT, this);
    ui->btnExport->setEnabled(false);
}

void LogDetail::on_btnQuery_clicked()
{
    ui->btnQuery->setEnabled(false);

    LogInfo logInfo;
    logInfo.type = (LogType)ui->cbxLogType->currentData().toInt();
    QString startDateTime = ui->datetimeStart->dateTime().toString(FMT_S);
    QString endDateTime = ui->datetimeEnd->dateTime().toString(FMT_S);
    QString user;
    if (AuthManager::instance()->isManufacturer(currentUsername))
    {// 厂家账号，可以查看所有操作日志
        user = "";
    }
    else if (AuthManager::instance()->isAdministrator(currentUsername))
    {// 管理员，过滤掉掉厂家操作日志
       user = "!=" + AuthManager::instance()->manufacturer();
    }
    else
    {// 普通用户，只能查看自己的操作日志
        user = currentUsername;
    }

    info = sqlHelper->selectLogTimeAndType(logInfo, startDateTime, endDateTime, user);
    int count = info.size();
    UserLogger::log(QString("%1%2~%3%4\n>%5: %6").arg(tr("Query")).arg(startDateTime).arg(endDateTime).arg(ui->cbxLogType->currentText()).arg(tr("Records Count")).arg(count));

    ui->tableWidget->clearContents();

    if (count == 0)
    {
        ui->tableWidget->setRowCount(1);
        ui->tableWidget->setRowHeight(0, windowWidth >= 1280 ? 400 : 260);
        ui->tableWidget->setSpan(0,0,1,4);
        QTableWidgetItem * item = new QTableWidgetItem(tr("No data yet"));
        item->setTextAlignment(Qt::AlignCenter);
        ui->tableWidget->setItem(0,0,item);
        ui->tableWidget->setShowGrid(false);
        ui->btnQuery->setEnabled(true);
        ui->btnExport->setEnabled(false);
        reportHtml.clear();
        return;
    }

    ui->tableWidget->setSpan(0,0,1,1);
    ui->tableWidget->setShowGrid(true);

    //genrate report html for exporting
    contentHtml.clear();
    contentHtml += generateTable(tableHeader, info);

    ui->tableWidget->setRowCount(count);
    //show log detail
    for (int i = 0; i < count; i++)
    {
        int rowHeight = 50;
        ui->tableWidget->setRowHeight(i,rowHeight);
        ui->tableWidget->setItem(i,0,new QTableWidgetItem(info[i].datetime));  //dateTime
        ui->tableWidget->setItem(i,1,new QTableWidgetItem(info[i].username)); //username
        ui->tableWidget->setItem(i,2,new QTableWidgetItem(info[i].detail));  //log description
        if (info[i].detail.contains("\n"))
        {// 自适应多行显示
            ui->tableWidget->resizeRowToContents(i);
        }

        for (int j = 0; j < 2; j++)
        {
            ui->tableWidget->item(i, j)->setTextAlignment(Qt::AlignCenter);
        }
    }

    ui->btnQuery->setEnabled(true);
    ui->btnExport->setEnabled(true);
}

void LogDetail::setWidgetVisibleSlot(int permission)
{
    AuthManager::instance()->showControls(this, permission);
    ui->btnExport->setEnabled(false);
    ui->tableWidget->setRowCount(0);
}

void LogDetail::retranslateUiSlot()
{
    ui->retranslateUi(this);
    retranslateLogType();
    retranslateTable();
}

void LogDetail::initWidget()
{
    initTableHeader();
    setShadow({ui->cbxLogType,ui->widget_2,ui->widget_3});
    //设置强焦点策略,这样输入法面板隐藏以后单击界面不会弹出
//    this->setFocusPolicy(Qt::StrongFocus);
    ui->tableWidget->setProperty("noinput",true);//不需要虚拟键盘
    //修改Combobox样式
    ui->cbxLogType->setView(new QListView());
    int headerHeight = 47;
    ui->tableWidget->horizontalHeader()->setFixedHeight(headerHeight);
    ui->tableWidget->verticalHeader()->hide();
    resizeTableColumnWidth();
    ui->tableWidget->horizontalHeader()->setStretchLastSection(true);//最后一个单元格扩展
    ui->cbxLogType->clear();
    retranslateLogType();
}

void LogDetail::resizeTableColumnWidth()
{
    if (windowWidth >= 1280)
    {
        ui->widget_2->setFixedWidth(250);
        ui->btnDatetimeStart->setFixedWidth(250);
        ui->datetimeStart->setFixedWidth(250);
        ui->widget_3->setFixedWidth(250);
        ui->btnDatetimeEnd->setFixedWidth(250);
        ui->datetimeEnd->setFixedWidth(250);

        ui->tableWidget->setColumnWidth(0,260);
        ui->tableWidget->setColumnWidth(1,130);
    }
    else
    {
        ui->tableWidget->setColumnWidth(0,120);
        ui->tableWidget->setColumnWidth(1,100);
    }
}

void LogDetail::retranslateTable()
{
    initTableHeader();
}

void LogDetail::retranslateLogType()
{
    if (ui->cbxLogType->count() <= 0)
    {// 初始化
        ui->cbxLogType->addItem(tr("OperationLog"), 0);
        ui->cbxLogType->addItem(tr("ErrorLog"), 2);
    }
    else
    {// 切换翻译
        ui->cbxLogType->setItemText(0, tr("OperationLog"));
        ui->cbxLogType->setItemText(2, tr("ErrorLog"));
    }
}

void LogDetail::initTableHeader()
{
    tableHeader.clear();
    tableHeader.append(tr("Time"));
    tableHeader.append(tr("Operator"));
    tableHeader.append(tr("Description"));

    ui->tableWidget->clear();
    ui->tableWidget->setColumnCount(tableHeader.count());

    for (int i = 0; i < ui->tableWidget->columnCount(); i++)
    {
        ui->tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(tableHeader.at(i)));
    }
}

QString LogDetail::generateTable(QStringList header, QList<LogInfo> info)
{
    QString html;
    html += QString("<table width='100%' border='1' style='border-collapse:collapse;' bordercolor='gray'>");
    //tr = table row, th = table header
    html += "<tr style='background-color:gray'>";
    int columnCount = header.count();
    for (int i = 0; i < columnCount; i++) {
        html += QString("<th>%1</th>").arg(header.at(i)) ;
    }
    html += "</tr>";

    //td = table data
    int dataRowCount = info.size();
    for (int i = 0; i < dataRowCount; i++) {
        html += "<tr>";

        html += QString("<td>%1</td>").arg(info[i].datetime);
        html += QString("<td>%1</td>").arg(info[i].code);
        html += QString("<td>%1</td>").arg(info[i].detail);

        html += "</tr>";
    }
    html += "</table>";
    return html;
}

void LogDetail::on_btnDatetimeStart_clicked()
{
    dateTimePicker->show();
    dateTimePicker->setWhatsThis("logdetail_start_datetimepicker");
    dateTimePicker->setDateTime(ui->datetimeStart->dateTime());
}


void LogDetail::on_btnDatetimeEnd_clicked()
{
    dateTimePicker->show();
    dateTimePicker->setWhatsThis("logdetail_end_datetimepicker");
    dateTimePicker->setDateTime(ui->datetimeEnd->dateTime());
}

void LogDetail::changeDateTime(QDateTime dateTime, QString whatsThis)
{
    if (whatsThis == "logdetail_start_datetimepicker") {
        ui->datetimeStart->setDateTime(dateTime);
    } else if (whatsThis == "logdetail_end_datetimepicker") {
        ui->datetimeEnd->setDateTime(dateTime);
    }
}

void LogDetail::setCurrentTimeSlot(int type)
{
    if(TimeSetType::LOG_START == type)
    {
        QDateTime dateTime = QDateTime::currentDateTime();
        ui->datetimeEnd->setDateTime(dateTime);
    }
}

void LogDetail::pdfSaveDone(const QString &info, const QString &path)
{
    UserLogger::log(info);

    MsgBox msgBox;
    msgBox.setTitle(tr("LogDetail"));
    msgBox.setText(info);
    msgBox.setInformativeText(path);
    msgBox.setBtnCancelVisible(false);
    msgBox.exec();

    ui->btnExport->setEnabled(true);
    Loading::hideLoading();
}
